import 'package:flutter/material.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import '../../resources/kq_theme_colors.dart';
import 'package:kq_flutter_core_widget/utils/text_input_format_utils.dart';

import '../../config/kq_global.dart';
import '../../resources/images.dart';
import '../../resources/kq_images.dart';
import '../../theme/kq_theme_manager.dart';
import '../divider/kq_divider.dart';
import '../textFiled/kq_textfiled.dart';
import 'entity/kq_form_entity.dart';

/// 通用表单组件 - 纯数量
///
/// [ItemType.onlyNumber]
///
/// 是否必填 + 左边标题 + 数量减按钮  + 数量输入框 + 数量加按钮 + 自定义右边控件
///
/// 结合 KqFormEntity 使用
///
/// 标题：title
/// 选择提示：hint
/// 数字值使用：qty
///
/// @author 周卓
///
class KqOnlyNumberItemView extends StatefulWidget {
  final KqFormEntity entity;

  /// 输入变化回调
  final ValueChanged<String>? onChanged;

  const KqOnlyNumberItemView({Key? key, required this.entity, this.onChanged})
      : super(key: key);

  @override
  KqOnlyNumberItemViewState createState() => KqOnlyNumberItemViewState();
}

class KqOnlyNumberItemViewState extends State<KqOnlyNumberItemView> {
  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  @override
  void initState() {
    widget.entity.widgetState = this;
    super.initState();
  }

  /// 点击减号
  void _onDec() {
    var qty = widget.entity.qty;
    if ((qty - widget.entity.qtyStep) >= widget.entity.minQty) {
      _onValueChanged((widget.entity.qty - widget.entity.qtyStep).toString());
    }
  }

  /// 点击加号
  void _onPlus() {
    var qty = widget.entity.qty;
    if (widget.entity.maxQty == null ||
        (qty + widget.entity.qtyStep) <= widget.entity.maxQty!) {
      _onValueChanged((qty + widget.entity.qtyStep).toString());
    }
  }

  /// 输入框数值变化
  void _onValueChanged(String text) {
    setState(() {
      widget.entity.qty = text.isEmpty ? widget.entity.minQty : num.parse(text);
      if (widget.entity.qty < widget.entity.minQty) {
        widget.entity.qty = widget.entity.minQty;
        widget.entity.valueForShow = widget.entity.qty.toString();
        widget.entity.valueForSubmit = widget.entity.qty.toString();
      } else if (widget.entity.maxQty != null) {
        if (widget.entity.qty > widget.entity.maxQty!) {
          widget.entity.qty = widget.entity.maxQty!;
          widget.entity.valueForShow = widget.entity.qty.toString();
          widget.entity.valueForSubmit = widget.entity.qty.toString();
        } else {
          widget.entity.valueForShow = text;
          widget.entity.valueForSubmit = text;
        }
      }
    });
    if (widget.entity.onChanged != null) {
      widget.entity.onChanged!(text);
    }
    if (widget.onChanged != null) {
      widget.onChanged!(text);
    }
  }

  // 减号能不能点
  bool _decAble() {
    return (widget.entity.qty - widget.entity.qtyStep) >= widget.entity.minQty;
  }

  // 加号能不能点
  bool _addAble() {
    return widget.entity.maxQty == null ||
        (widget.entity.qty + widget.entity.qtyStep) <= widget.entity.maxQty!;
  }

  @override
  Widget build(BuildContext context) {
    // 如果外层实体是反复重新创建的，则需要在此重新赋值
    widget.entity.widgetState = this;
    var bgColor = widget.entity.backgroundColor ?? KqThemeColors.bgDialog;
    return Visibility(
      visible: widget.entity.visible,
      child: Container(
        color: bgColor,
        child: Column(
          children: [
            Container(
              padding: EdgeInsets.only(
                  right: widget.entity.paddingHorizontal ??
                      KqThemeManager.instance
                          .getConfig()
                          .formConfig
                          .paddingHorizontal ??
                      24.r),
              child: Row(
                children: [
                  Expanded(
                    child: Container(
                      padding: EdgeInsets.only(
                          right: widget.entity.titleRightMargin ??
                              (widget.entity.title.isNotEmpty ? 40.r : 0)),
                      margin: EdgeInsets.symmetric(
                          vertical: widget.entity.paddingVertical ??
                              KqThemeManager.instance
                                  .getConfig()
                                  .formConfig
                                  .paddingVertical ??
                              24.r),
                      child: Row(
                        children: <Widget>[
                          /// 是否必填
                          Container(
                            alignment: Alignment.centerRight,
                            width: widget.entity.paddingHorizontal ??
                                KqThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .paddingHorizontal ??
                                24.r,
                            padding: EdgeInsets.only(right: 2.r),
                            child: Text(
                              "∗",
                              textAlign: TextAlign.center,
                              style: TextStyle(
                                  fontSize: KqThemeManager.instance
                                          .getConfig()
                                          .formConfig
                                          .mustInputFontSize ??
                                      24.sp,
                                  color: widget.entity.mustInput &&
                                          widget.entity.isEditable()
                                      ? KqThemeColors.textRed
                                      : KqThemeColors.bgTransparent),
                            ),
                          ),

                          /// 标题
                          LimitedBox(
                            maxWidth: KqThemeManager.instance
                                    .getConfig()
                                    .formConfig
                                    .titleMaxWidth ??
                                200.r,
                            child: Text(
                              widget.entity.title,
                              style: widget.entity.titleStyle ??
                                  TextStyle(
                                      fontSize: KqThemeManager.instance
                                              .getConfig()
                                              .formConfig
                                              .titleFontSize ??
                                          16.sp,
                                      color: widget.entity.titleColor ??
                                          KqThemeColors.text26),
                            ),
                          )
                        ],
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 24.r,
                    height: 1,
                  ),

                  /// 数量减
                  InkWell(
                    onTap: () => _onDec(),
                    child: Opacity(
                      opacity: _decAble() ? 1.0 : 0.5,
                      child: Image.asset(
                        Images.commonIcJs,
                        width: 52.r,
                        height: 52.r,
                        fit: BoxFit.contain,
                        package: KqGlobal.packageName,
                      ),
                    ),
                  ),
                  SizedBox(
                    width: 8.r,
                    height: 1,
                  ),

                  /// 数量输入框
                  SizedBox(
                    width: 78.r,
                    child: KqTextFiled(
                      inputType:
                          widget.entity.inputType ?? TextInputType.number,
                      multiline: false,
                      maxLines: 1,
                      enableClearButton: false,
                      editable: widget.entity.isEditable(),
                      textAlign: TextAlign.center,
                      newValue: widget.entity.valueForShow,
                      fontSize: KqThemeManager.instance
                              .getConfig()
                              .formConfig
                              .contentFontSize ??
                          24.sp,
                      defValue: widget.entity.qty.toString(),
                      placeHolder: widget.entity.minQty.toString(),
                      maxCharCount: widget.entity.maxCharCount,
                      inputFormatters: widget.entity.inputFormatters ??
                          TextInputFormatUtils.integer(),
                      onChanged: (value) => _onValueChanged(value),
                    ),
                  ),
                  SizedBox(
                    width: 8.r,
                    height: 1,
                  ),

                  /// 数量加
                  InkWell(
                    onTap: () => _onPlus(),
                    child: Opacity(
                      opacity: _addAble() ? 1.0 : 0.5,
                      child: Image.asset(
                        Images.commonIcZj,
                        width: 52.r,
                        height: 52.r,
                        fit: BoxFit.contain,
                        package: KqGlobal.packageName,
                      ),
                    ),
                  ),

                  /// 自定义右边控件
                  if (widget.entity.customRightView != null)
                    widget.entity.customRightView!(widget.entity)
                ],
              ),
            ),

            /// 自定义底部控件
            widget.entity.customBottomView != null
                ? widget.entity.customBottomView!(widget.entity)
                : Container(),

            const KqDivider(),
          ],
        ),
      ),
    );
  }
}
